#include "BilibiliQRCodeGenerator.h"
#include <QDebug>

BilibiliQRCodeGenerator::BilibiliQRCodeGenerator(QObject *parent)
    : QObject(parent)
    , m_networkManager(new QNetworkAccessManager(this))
    , m_currentReply(nullptr)
    , m_isLoading(false)
{
    // 连接网络管理器的信号
    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &BilibiliQRCodeGenerator::onReplyFinished);
}

void BilibiliQRCodeGenerator::generateQRCode()
{
    if (m_isLoading) {
        qDebug() << "Already generating QR code, please wait...";
        return;
    }

    setIsLoading(true);
    setErrorMessage("");

    // 构建请求
    QNetworkRequest request;
    request.setUrl(QUrl("https://passport.bilibili.com/x/passport-login/web/qrcode/generate"));

    // 设置请求头，模拟浏览器
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
    request.setRawHeader("Accept", "application/json, text/plain, */*");
    request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
    request.setRawHeader("Accept-Encoding", "gzip, deflate, br");
    request.setRawHeader("Connection", "keep-alive");
    request.setRawHeader("Referer", "https://passport.bilibili.com/");

    // 发送GET请求
    m_currentReply = m_networkManager->get(request);

    // 连接错误处理信号
    connect(m_currentReply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error),
            this, &BilibiliQRCodeGenerator::onNetworkError);
}

void BilibiliQRCodeGenerator::onReplyFinished()
{
    if (!m_currentReply) {
        setIsLoading(false);
        return;
    }

    // 检查HTTP状态码
    int statusCode = m_currentReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (statusCode == 200) {
        // 读取响应数据
        QByteArray responseData = m_currentReply->readAll();

        // 解析JSON
        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError);

        if (parseError.error != QJsonParseError::NoError) {
            setErrorMessage("JSON解析错误: " + parseError.errorString());
            setIsLoading(false);
            emit qrcodeGenerated(false, "", "");
            m_currentReply->deleteLater();
            m_currentReply = nullptr;
            return;
        }

        QJsonObject rootObject = doc.object();
        int code = rootObject["code"].toInt();
        QString message = rootObject["message"].toString();

        if (code == 0) {
            // 成功获取数据
            QJsonObject dataObject = rootObject["data"].toObject();
            QString url = dataObject["url"].toString();
            QString qrcodeKey = dataObject["qrcode_key"].toString();

            setUrl(url);
            setQrcodeKey(qrcodeKey);

            qDebug() << "QR Code generated successfully:";
            qDebug() << "URL:" << url;
            qDebug() << "QR Code Key:" << qrcodeKey;

            emit qrcodeGenerated(true, url, qrcodeKey);
        } else {
            // 服务器返回错误
            setErrorMessage(QString("服务器错误 (code: %1): %2").arg(code).arg(message));
            emit qrcodeGenerated(false, "", "");
        }
    } else {
        // HTTP错误
        setErrorMessage(QString("HTTP错误: %1").arg(statusCode));
        emit qrcodeGenerated(false, "", "");
    }

    setIsLoading(false);
    m_currentReply->deleteLater();
    m_currentReply = nullptr;
}

void BilibiliQRCodeGenerator::onNetworkError(QNetworkReply::NetworkError error)
{
    QString errorString = m_currentReply ? m_currentReply->errorString() : "Unknown network error";
    setErrorMessage("网络错误: " + errorString);
    setIsLoading(false);
    emit qrcodeGenerated(false, "", "");

    qDebug() << "Network error:" << error << errorString;
}

void BilibiliQRCodeGenerator::setUrl(const QString& url)
{
    if (m_url != url) {
        m_url = url;
        emit urlChanged();
    }
}

void BilibiliQRCodeGenerator::setQrcodeKey(const QString& key)
{
    if (m_qrcodeKey != key) {
        m_qrcodeKey = key;
        emit qrcodeKeyChanged();
    }
}

void BilibiliQRCodeGenerator::setIsLoading(bool loading)
{
    if (m_isLoading != loading) {
        m_isLoading = loading;
        emit isLoadingChanged();
    }
}

void BilibiliQRCodeGenerator::setErrorMessage(const QString& message)
{
    if (m_errorMessage != message) {
        m_errorMessage = message;
        emit errorMessageChanged();
    }
}
